package com.tpc.client.modules.core.organisation.datasource;

import com.tpc.client.modules.core.organisation.service.OrganisationService;
import com.tpc.client.modules.core.organisation.service.OrganisationServiceAsync;
import com.tpc.dao.extend.Organisation;

import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.tpc.client.systeme.core.datasource.GwtRpcDataSource;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.types.FieldType;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.util.Page;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.validator.MaskValidator;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.tpc.client.systeme.core.Systeme;

public class OrganisationFormDS extends GwtRpcDataSource {

    Systeme systeme = null;
    ListGrid RELOAD_GRID;
    DynamicForm FORM_TOUPDATE;
    String MODULEID = null;

    public OrganisationFormDS(String strID,ListGrid gridparam,DynamicForm formParam,Systeme sysParam,String Moduleparam) {
            setID(strID);
            systeme = sysParam;
            RELOAD_GRID = gridparam;
            FORM_TOUPDATE = formParam;
            MODULEID = Moduleparam;
            
            DataSourceField fldOrganisationId = new DataSourceField();
            fldOrganisationId.setName(MODULEID+"_form_id");
            fldOrganisationId.setRequired(Boolean.TRUE);
            fldOrganisationId.setType(FieldType.INTEGER);
            fldOrganisationId.setPrimaryKey(Boolean.TRUE);
            fldOrganisationId.setHidden(Boolean.FALSE);
            
            DataSourceField fldOrganisationName = new DataSourceField();
            fldOrganisationName.setName(MODULEID+"_form_name");
            fldOrganisationName.setRequired(Boolean.TRUE);
            fldOrganisationName.setType(FieldType.TEXT);
            fldOrganisationName.setPrimaryKey(Boolean.FALSE);
            fldOrganisationName.setHidden(Boolean.FALSE);
            
            DataSourceField fldOrganisationNote = new DataSourceField();
            fldOrganisationNote.setName(MODULEID+"_form_note");
            fldOrganisationNote.setRequired(Boolean.TRUE);
            fldOrganisationNote.setType(FieldType.TEXT);
            fldOrganisationNote.setPrimaryKey(Boolean.FALSE);
            fldOrganisationNote.setHidden(Boolean.FALSE);
   
            DataSourceField fldOrganisationType = new DataSourceField();
            fldOrganisationType.setName(MODULEID+"_form_type");
            fldOrganisationType.setRequired(Boolean.FALSE);
            fldOrganisationType.setType(FieldType.TEXT);
            fldOrganisationType.setPrimaryKey(Boolean.FALSE);
            fldOrganisationType.setHidden(Boolean.FALSE);
            
            DataSourceField fldOrganisationCategory = new DataSourceField();
            fldOrganisationCategory.setName(MODULEID+"_form_category");
            fldOrganisationCategory.setRequired(Boolean.FALSE);
            fldOrganisationCategory.setType(FieldType.TEXT);
            fldOrganisationCategory.setPrimaryKey(Boolean.FALSE);
            fldOrganisationCategory.setHidden(Boolean.FALSE);
           
            DataSourceField fldOrganisationCreated =  new DataSourceField();
            fldOrganisationCreated.setName(MODULEID+"_form_created");
            fldOrganisationCreated.setRequired(Boolean.FALSE);
            fldOrganisationCreated.setType(FieldType.TEXT);
            fldOrganisationCreated.setPrimaryKey(Boolean.FALSE);
            fldOrganisationCreated.setHidden(Boolean.FALSE);
            
            DataSourceField fldOrganisationModified =  new DataSourceField();
            fldOrganisationCreated.setName(MODULEID+"_form_modified");
            fldOrganisationCreated.setRequired(Boolean.FALSE);
            fldOrganisationCreated.setType(FieldType.TEXT);
            fldOrganisationCreated.setPrimaryKey(Boolean.FALSE);
            fldOrganisationCreated.setHidden(Boolean.FALSE);
            
            setFields(fldOrganisationId,fldOrganisationName,fldOrganisationNote,fldOrganisationType,fldOrganisationCategory,fldOrganisationCreated,fldOrganisationModified);

    }

    @Override
    protected void executeFetch (final String requestId, final DSRequest request, final DSResponse response) {
       Criteria criteria = request.getCriteria();
       String strId = "-1";
       if (criteria != null) {
           strId = criteria.getAttributeAsString("id");           
       }      
       OrganisationServiceAsync service = GWT.create(OrganisationService.class);
        ServiceDefTarget endpoint = (ServiceDefTarget) service;
        endpoint.setServiceEntryPoint(systeme.getPageUrl()+"/com.tpc.organisation/orgloader");
        service.loadForm(strId,new AsyncCallback<Organisation> () {
            public void onFailure (Throwable caught) {
                systeme.stopLoading();
                response.setStatus (RPCResponse.STATUS_FAILURE);
                processResponse (requestId, response);         
            }
            public void onSuccess (Organisation result) {
                ListGridRecord[] list = null;
                if (result != null) {
                    list = getRecordFromObject(result);
                }                
                response.setData(list);
                processResponse(requestId, response);
                systeme.stopLoading();
            }
        });
    }

    @Override
    protected void executeAdd (final String requestId, final DSRequest request, final DSResponse response) {
        JavaScriptObject data = request.getData();
        Record dataToSave = new Record (data);
        Organisation organisation = null;//getObjectFromRecord(dataToSave);
        if (organisation.isValidated()) {
	        OrganisationServiceAsync service = GWT.create (OrganisationService.class);
	        ServiceDefTarget endpoint = (ServiceDefTarget) service;
	        endpoint.setServiceEntryPoint(systeme.getPageUrl()+"/com.tpc.organisation/orgloader");
	        service.addForm(organisation, new AsyncCallback<Organisation> () {
	            public void onFailure (Throwable caught) {
	                systeme.stopLoading();
	                response.setStatus (RPCResponse.STATUS_FAILURE);
	                processResponse (requestId, response);
	                systeme.handleServerException(caught);
	            }
	            public void onSuccess (Organisation result) {
	                ListGridRecord[] list = new ListGridRecord[1];
	                list[0] = new ListGridRecord();
	                response.setData(list);
	                processResponse(requestId, response);
	                RELOAD_GRID.invalidateCache();
	                RELOAD_GRID.fetchData();
	                systeme.getAppBar().updateTab(systeme.getAppBar().getTab(MODULEID),systeme.getOrganisationUI().getList());
	            }
	        });
        }
        else {
            systeme.stopLoading();
            SC.say(systeme.getDictionary().MISSING_MANDATORY_FIELD());
        }
    }

    @Override
    protected void executeUpdate (final String requestId, final DSRequest request, final DSResponse response) {
        JavaScriptObject data = request.getData();
        Record dataToSave = new Record (data);
        Organisation organisation = null;//getObjectFromRecord(dataToSave);
        if (organisation.isValidated()) {
            OrganisationServiceAsync service = GWT.create (OrganisationService.class);
            ServiceDefTarget endpoint = (ServiceDefTarget) service;
            endpoint.setServiceEntryPoint(systeme.getPageUrl()+"/com.tpc.organisation/orgloader");
            service.updateForm(organisation, new AsyncCallback<Organisation> () {
                public void onFailure (Throwable caught) {
                    systeme.stopLoading();
                    response.setStatus (RPCResponse.STATUS_FAILURE);
                    processResponse (requestId, response);
                    systeme.handleServerException(caught);
                }
                public void onSuccess (Organisation result) {
                    ListGridRecord[] list = new ListGridRecord[1];
                    if (result != null) {
                        list = new ListGridRecord[1];
                        list[0] = new ListGridRecord();
                    }
                    response.setData(list);
                    processResponse(requestId, response);

                    ListGridRecord[] records = RELOAD_GRID.getRecords();
                    if (records != null) {
                        for (int i = 0; i < records.length; i++) {
                            if (new Integer(records[i].getAttribute("organisation_liste_id")).intValue() == result.getId()) {
                                int position = RELOAD_GRID.getRecordIndex(records[i]);
                                //setDataToGrid(result,RELOAD_GRID,position);
                                RELOAD_GRID.refreshRow(position);
                            }
                        }
                    }

                    systeme.getAppBar().updateTab(systeme.getAppBar().getTab(MODULEID),systeme.getOrganisationUI().getList());
                }
            });
        } else {
            systeme.stopLoading();
            SC.say(systeme.getDictionary().MISSING_MANDATORY_FIELD());
        }
    }

    @Override
    protected void executeRemove (final String requestId, final DSRequest request, final DSResponse response) {
        JavaScriptObject data = request.getData();
        Record dataToSave = new Record (data);
        String id = dataToSave.getAttribute("id");
            OrganisationServiceAsync service = GWT.create (OrganisationService.class);
            ServiceDefTarget endpoint = (ServiceDefTarget) service;
            endpoint.setServiceEntryPoint(systeme.getPageUrl()+"/com.tpc.organisation/orgloader");
            service.removeForm(id, new AsyncCallback<Integer> () {
                public void onFailure (Throwable caught) {
                    systeme.stopLoading();
                    response.setStatus (RPCResponse.STATUS_FAILURE);
                    processResponse (requestId, response);
                    systeme.handleServerException(caught);
                }
                public void onSuccess (Integer result) {
                	SC.say(systeme.getDictionary().ITEM_DELETED());
                	systeme.stopLoading();
                	systeme.getAppBar().updateTab(systeme.getAppBar().getTab(MODULEID),systeme.getOrganisationUI().getList());
                }
            });
    }
    
    public ListGridRecord[] getRecordFromObject(Organisation result) {
GWT.log("here 66");    	
    	ListGridRecord[] lists = null;
    	if (result != null) {
    		 lists = new ListGridRecord[1];
             lists[0] = new ListGridRecord();
             lists[0].setAttribute(MODULEID+"_form_id", result.getId());
             lists[0].setAttribute(MODULEID+"_form_name", result.getName());
             lists[0].setAttribute(MODULEID+"_form_notes", result.getDescription());
             
             int typeid = 0;
             if (result.getType() != null) {
            	 typeid = result.getType().getId();
             }
             if (typeid > 0) {
            	 lists[0].setAttribute(MODULEID+"_form_type",new Integer(typeid).toString());
             }
             
             int categoryid = 0;
             if (result.getCategory() != null) {
            	 categoryid = result.getCategory().getId();
             }
             if (categoryid > 0) {
            	 lists[0].setAttribute(MODULEID+"_form_category",new Integer(categoryid).toString());
             }
             
             lists[0].setAttribute(MODULEID+"_form_created", result.getCreatedDateAsString());
             lists[0].setAttribute(MODULEID+"_form_created", result.getModifiedDateAsString());
    	}
    	return lists;
    }
    

}
